/**
 * 宽带预约列表
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var opponentList = new Array();
  var DATA_OPERATORS = ["", "联通", "电信"],
      DATA_PROD_TYPE = ["", "IDC", "专线", "集团电话", "物联网"];
  /*
  封装参数
  */
  var getMyParams = function(id,operator,prod_type) {
    var params = "?";
    var myParam = getParams();
    console.log("myParam=" + myParam);
    if (myParam) {
      params += myParam;
      if (id) {
        params += "&";
      }
    }
    if (id) {
      params += "id=" + id;
    }
    if (operator&&prod_type) {
      params += "&operator="+operator+"&prod_type="+prod_type;
    }
    
    console.log("params=" + params);
    return params;
  };

  var bind = function(object, clickFunc) {
    itemOnClick(object, clickFunc);
  }

  var itemOnClick = function(object, clickFunc) {
    $(object).off("click"); //取消li事件
    /*li事件*/
    $(object).on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
      }
      clickFunc(this);
      event.stopPropagation();
    });
  }


  var groupClickFunc = function(object) {
      var id = $(object).find("input[name='opponent_id']").val(),
          operator = $(object).find("input[name='operator']").val(),
          prod_type = $(object).find("input[name='prod_type']").val();
      getMyParams(id,operator,prod_type);
      window.location.href = "opponent_detail.html" + getMyParams(id,operator,prod_type);
    }
    /*
    显示数据
    */
  var showOpponentData = function(data) {
    if (data instanceof Array) {
      list = data.sort(function(a, b) {
        return new Date(b.CREATE_TIME) - new Date(a.CREATE_TIME)
      });
      for (var i = 0; i < list.length; i++) {
        list[i].OPERATOR = DATA_OPERATORS[list[i].OPERATOR];
        list[i].PROD_TYPE = DATA_PROD_TYPE[list[i].PROD_TYPE];
        opponentList.push(list[i]);
      }
    } else if (data instanceof Object) {
      data.OPERATOR = DATA_OPERATORS[data.OPERATOR];
      data.PROD_TYPE = DATA_PROD_TYPE[data.PROD_TYPE];
      opponentList.push(data);
    }
    var $tpl = $('#amz-group-list');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
      list: opponentList,
      "error": "没有对手信息"
    };

    $("#opponent-list").children('li').remove();
    $("#opponent-list").children('div').remove();

    var html = template(myData);
    $tpl.before(html);
    bind("#opponent-list > li", groupClickFunc);
  };


  var loadOpponentData = function(pageNumber, operator) {
    showLoadingBar($("#loadingbar"), true);
    groupNo = getParamValue("group_no");
    console.log("groupNo=" + groupNo);
    
    params = {
        // "requestData": "<CUST_CODE>2800342235</CUST_CODE><OPERATOR>1</OPERATOR><PROD_TYPE>1</PROD_TYPE>"
        "requestData": "<CUST_CODE>"+ groupNo +
        "</CUST_CODE><OPERATOR>"+operator+
        "</OPERATOR><PROD_TYPE></PROD_TYPE>"
    };
    $.ajax({
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(params),
      // url: "../../../opponent/getOpponentList?group_name=&group_no=" + groupNo + "&operator=" + operator,
      url: Constants.restHost + "rest/opp/compProdQryList",
      dataType: "json",
      async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingbar"), false);
        console.log("data = " + data);
        pageData = data.rtnCode;
        console.info(data.rtnCode);
        if (data.rtnCode != 1000) {
          console.log("获取RPC接口返回失败！code:" + data.rtnCode);
          return;
        }
        if (data.return.HEADER.RESPONSE.CODE != 0000) {
          console.log("获取信息接口返回失败！code:" + data.return.HEADER.RESPONSE.CODE);
          return;
        }
        showOpponentData(data.return.RESULT.PROD_LIST);
      },
      error: function(textStatus) {
        showLoadingBar($('#loadingbar'), false);;
        console.info("request error:");
      }
    });
  };

  $(function() {
    /*滚动条*/
    var $doc = $(document);
    $doc.scroll(function() {
      console.log("height = " + ($doc.height() - $(window).height()));
      console.log("scrollTop = " + Math.ceil($doc.scrollTop()));
      console.log("Math.ceil($doc.scrollTop()) = " + Math.ceil($doc.scrollTop()));
      if (Math.ceil($doc.scrollTop()) >= ($doc.height() - $(window).height())) {
        var $msg = $("#no-data-msg");
        console.log("debug 1");
        if (!$.isEmptyObject(pageData)) {
          console.log("debug 2");
          if (!$msg.hasClass("am-hide")) {
            console.log("debug 3");
            $msg.addClass("am-hide");
          }
          console.log("pageNumber=" + pageNumber);
          pageNumber++;
          loadGroupData(pageNumber);
        } else {
          console.log("debug 5");
          if ($msg.hasClass("am-hide")) {
            console.log("debug 6");
            $msg.removeClass("am-hide");
          }
        }
      }
    });


    $("#search_btn").on("click", function() {
      operator = $("#searchType").val();
      console.log("operator="+operator);
      if(!DATA_OPERATORS[operator] ){
        $("#search").val("查询：所有");
      }else{
        $("#search").val("查询："+DATA_OPERATORS[operator]);
      }
      console.log("operator=" + DATA_OPERATORS[operator]);
      if (DATA_OPERATORS[operator] === "") {
        operator = "";
      }
      pageNumber = 0;
      opponentList = [];
      loadOpponentData(pageNumber, operator);
    });
    $("#search").on("click", function() {
      $('#search-modal').modal('open');
    });
    $("#add-btn").on("click", function() {
      console.log("add btn clicked");
      window.location.href = "idc_add.html?" + getParams();
    });
    $("#search").val("查询：所有");
    loadOpponentData(pageNumber, "");
  });
})(jQuery);